#include <iostream>
#include <iostream>
#include <memory>
#include <string>
#include <cstring>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Comm.hpp"

void Usage(const std::string &proc)
{
    std::cout << "Usage:\n\t" << proc << " serverip serverport" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(Usage_Err);
    }

    std::string serverip = argv[1];
    int16_t serverport = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "create socket fail:" << strerror(errno) << std::endl;
        exit(Socket_Err);
    }

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);
    if (connect(sockfd, CONV(server), sizeof(server)) != 0)
    {
        std::cout << "connect fail: " << strerror(errno) << std::endl;
        exit(2);
    }
    while (true)
    {
        std::string inbuffer;
        std::cout << "Please say#";
        getline(std::cin, inbuffer);
        ssize_t n = write(sockfd, inbuffer.c_str(), inbuffer.size());
        if (n > 0)
        {
            char buffer[1024];
            ssize_t m = read(sockfd, buffer, sizeof(buffer) - 1);
            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << "get a echo message#" << buffer << std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }

    return 0;
}